package com.gzhryc.shared_device.oem.code.device.services;

import com.gzhryc.common.logging.Logger;
import com.gzhryc.jdbc.Conditions;
import com.gzhryc.jdbc.MultiDBTools;
import com.gzhryc.shared_device.oem.code.device.dao.AgentRelationCDCZDeviceDao;
import com.gzhryc.shared_device.oem.code.device.dao.models.AgentRelationCDCZDevice;
import com.gzhryc.shared_device.oem.code.device.services.dto.AgentRelationCDCZDeviceSearch;

import java.sql.SQLException;
import java.util.List;

public class AgentRelationCDCZDeviceService {

    static Logger log = Logger.getLogger(AgentRelationCDCZDeviceService.class);

    public static AgentRelationCDCZDeviceService self() {
        return MultiDBTools.getService(AgentRelationCDCZDeviceService.class, true);
    }

    public static AgentRelationCDCZDeviceService self(String jdbcKey) {
        return MultiDBTools.getService(jdbcKey, AgentRelationCDCZDeviceService.class, true);
    }

    AgentRelationCDCZDeviceDao dao;

    public AgentRelationCDCZDeviceService(String jdbcKey) {
        dao = new AgentRelationCDCZDeviceDao(jdbcKey);
    }

    public List<AgentRelationCDCZDevice> findJoinBySearch(AgentRelationCDCZDeviceSearch search, Integer pageNo, Integer pageLimit){
        Conditions conditions = dao.buildConditions(search);
        conditions.and().is("device.user_id",search.getUserId());
        conditions.and().is("device.place_id",search.getPlaceId());
        conditions.and().is("relationDevice.relation_user_id",search.getRelationUserId());
        conditions.and().likeBoth("deviceSn",search.getTrim()).or().likeBoth("device.place_name",search.getTrim());
        if(search.getDeploy() != null){
            if(search.getDeploy()){
                conditions.and().isNotNull("device.place_id");
            }else{
                conditions.and().isNull("device.place_id");
            }
        }
        try {
            return dao.findJoinByCondition(conditions,pageNo,pageLimit);
        } catch (SQLException e) {
            log.error(e.getMessage(),e);
        }
        return null;
    }

    public Long countJoinBySearch(AgentRelationCDCZDeviceSearch search){
        Conditions conditions = dao.buildConditions(search);
        conditions.and().is("device.user_id",search.getUserId());
        conditions.and().is("device.place_id",search.getPlaceId());
        conditions.and().is("relationDevice.relation_user_id",search.getRelationUserId());
        conditions.and().likeBoth("deviceSn",search.getTrim()).or().likeBoth("device.place_name",search.getTrim());
        if(search.getDeploy() != null){
            if(search.getDeploy()){
                conditions.and().isNotNull("device.place_id");
            }else{
                conditions.and().isNull("device.place_id");
            }
        }
        try {
            return dao.countJoin(conditions);
        } catch (SQLException e) {
            log.error(e.getMessage(),e);
        }
        return 0L;
    }

}
